import { Injectable } from '@nestjs/common';
import { CreateSessionDto, CreateMessageDto } from './dto/chat.dto';
import OpenAI from 'openai';
import { Response } from 'express';
import { InjectRepository } from '@nestjs/typeorm';
import { Between, Repository } from 'typeorm';
import { Session } from './entities/session.entity';
import { CustomException, ErrorCode } from 'src/common/exceptions/custom.exception';
import { Message } from './entities/message.entity';
import dayjs from 'dayjs';
import { notEmpty } from 'src/utils/func';
@Injectable()
export class ChatService {
  client: OpenAI;
  constructor(
    @InjectRepository(Session)
    private sessionRepo: Repository<Session>,
    @InjectRepository(Message)
    private MessageRepo: Repository<Message>,
  ) {
    this.client = new OpenAI({ baseURL: 'https://api.deepseek.com', apiKey: 'sk-3244f81785d247168e203b25c37280a3' });
  }

  /** 对话 */
  async create(body: CreateMessageDto, res: Response) {
    const completion = await this.client.chat.completions.create({
      model: 'deepseek-chat',
      messages: [{ role: 'system', content: body.question }],
      stream: true,
    });
    let dataStr = ``;
    for await (const chunk of completion) {
      const sseStr = `data: ${JSON.stringify(chunk)}\n\n`;
      dataStr += sseStr;
      res.write(sseStr);
    }
    res.end();
    this.createMessage(body);
  }

  /** 创建会话 */
  async createSession(body: CreateSessionDto) {
    try {
      // 如果会话名不传，默认存一个会话名 `日期+行号`
      let sessionName = '';
      if (!body.name) {
        const today = dayjs();
        const startOfDay = today.startOf('day').toDate();
        const endOfDay = today.endOf('day').toDate();
        const data = await this.sessionRepo.count({
          where: {
            createTime: Between(startOfDay, endOfDay),
          },
        });
        sessionName = `${today.format('YYYY-MM-dd')}-${data + 1}`;
      }
      const newSession = this.sessionRepo.create({
        ...body,
        name: body.name ? body.name : sessionName,
      });
      return this.sessionRepo.save(newSession);
    } catch (error) {
      throw new CustomException(ErrorCode.ERR_50001, error, 500);
    }
  }

  /** 根据当前人的id查询所有会话 */
  async getAllSessionByUserId(id: string) {
    if (!notEmpty(id)) {
      throw new CustomException(ErrorCode.ERR_10000, 'userId缺失', 400);
    }
    return await this.sessionRepo.find({
      where: { userId: +id, isDelete: 0 },
      order: { createTime: 'DESC' },
    });
  }

  /** 创建消息 */
  async createMessage(body: CreateMessageDto) {
    const newMessage = this.MessageRepo.create(body);
    return this.MessageRepo.save(newMessage);
  }

  /** 根据会话id查询消息 */
  async getMessageBySessionId(id: string) {
    if (!notEmpty(id)) {
      throw new CustomException(ErrorCode.ERR_10000, 'sessionId缺失', 400);
    }
    return await this.MessageRepo.find({
      where: {
        session: { id, isDelete: 0 },
      },
    });
  }

  /**
   * 前端调用示例
   * async chat() {
      const response = await fetch("http://localhost:8085/api/chat/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content: "介绍一下你自己" }),
      });
      const reader = response.body.getReader();
      const decoder = new TextDecoder("utf-8");

      let done = false;
      while (!done) {
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (value) {
          const chunk = decoder.decode(value, { stream: true });
          console.log("🚀 ~ handleQuery ~ chunk:", chunk);
          // 在这里处理每个数据块
        }
      }
    },
   */
}
